package com.kungfuhacking.wristbandpro.chat.presenter;

import android.os.Bundle;
import android.util.Log;

import com.kungfuhacking.wristbandpro.base.presenter.BasePresenter;
import com.kungfuhacking.wristbandpro.chat.activity.ChatActivity;
import com.kungfuhacking.wristbandpro.chat.view.IFragmentChatView;
import com.kungfuhacking.wristbandpro.database.DatabaseManager;
import com.kungfuhacking.wristbandpro.mqtt.MqttConstant;
import com.kungfuhacking.wristbandpro.mqtt.bean.MessageBean;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Aaron on 17/5/17.
 */

public class IFragmentChatPresenter implements BasePresenter {

    private IFragmentChatView iFragmentChatView;
    private List<MessageBean> mChatLists = new ArrayList<>();
    private String TAG = getClass().getSimpleName();

    public IFragmentChatPresenter(IFragmentChatView iFragmentChatView) {
        this.iFragmentChatView = iFragmentChatView;
    }

    public void getRecentChatList() {

        Observable.create(new ObservableOnSubscribe<List<MessageBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<MessageBean>> e) throws Exception {

                Log.d(TAG, " 查询线程 : " + Thread.currentThread().getName());

                e.onNext(DatabaseManager.getInstance().getChatListFromTopics(iFragmentChatView.getMyContext(), iFragmentChatView.getSp().getString(MqttConstant.USERID, ""))
                );

            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<MessageBean>>() {

                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(List<MessageBean> chatLists) {
                        mChatLists = chatLists;
                        Log.d(TAG, "查询到的聊天记录个数:" + chatLists.size());
                        iFragmentChatView.setAdapterData(chatLists);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "查询出错: " + e.getLocalizedMessage() + ", " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 进入聊天页面
     *
     * @param mb
     */
    public void enterChat(MessageBean mb) {

//        //单聊 和 跟系统聊天
//        if (mb.channelId.startsWith(MqttConstant.START_SINGLE) || mb.channelId.startsWith(MqttConstant.START_S))
//
//            if (!iFragmentChatView.getSp().getString(MqttConstant.USERID, "").equals(mb.sendId)) { //私聊的时候发送者为对方
//                mb.receiveName = mb.sendName;
//                mb.receiveId = mb.sendId;
//                mb.receivePic = mb.sendPic;
//            }

        Bundle b = new Bundle();
        b.putParcelable("contact", mb);
        iFragmentChatView.nextActivityWithBundle(ChatActivity.class, b);
    }

    /**
     * 收到mqtt消息
     *
     * @param mb
     */
    public void receiveMsg(MessageBean mb) {

        switch (mb.operationStyle) {

//            case MqttConstant.OFF_GROUP://退出群, 删除好友的 广播,在列表中删除该聊天的item
//
//                Log.d(TAG, "    退出群的 event    ");
//                exitGroup(mb);
//
//                break;

            case MqttConstant.RECEIVE_MESSAGE://接受到新的消息 (自己发的消息也会在这里调用)
                receiveChatMsg(mb);
                break;

            case MqttConstant.DELETE_RECENT_HISTORY://删除最近聊天记录

                //迭代集合,找到该条目
                for (MessageBean msb : mChatLists) {
                    if (msb.channelId != null && msb.channelId.equals(mb.channelId)) {

                        mChatLists.remove(msb);
                        mb.sendDate = msb.sendDate;
                        mChatLists.add(0, mb);

                        iFragmentChatView.setAdapterData(mChatLists);

                        return;
                    }
                }

                //列表中没有该聊天列表,增加该条目
                mChatLists.add(0, mb);//在0的位置上添加该聊天记录
                iFragmentChatView.setAdapterData(mChatLists);

                break;

        }

    }

    private void receiveChatMsg(MessageBean mb) {

        //迭代看最近聊天列表中是否有该聊天的item
        for (MessageBean msb : mChatLists) {
            if (msb.channelId != null && msb.channelId.equals(mb.channelId)) {
                mChatLists.remove(msb);
                mb.receiveName = msb.receiveName;
                mb.receivePic = msb.receivePic;
                mChatLists.add(0, mb);
                iFragmentChatView.setAdapterData(mChatLists);
                return;
            }
        }

        //列表中没有该聊天列表,增加该条目
        mChatLists.add(0, mb);//在0的位置上添加该聊天记录
        iFragmentChatView.setAdapterData(mChatLists);

    }


    /**
     * 清空该topic的历史聊天记录
     *
     * @param position
     */
    public void clearChatHistory(final int position) {

        if (mChatLists == null || mChatLists.size() < 1)
            return;

        final String topic = mChatLists.get(position).channelId;
        mChatLists.get(position).content = "";
        mChatLists.get(position).messageType = MqttConstant.MQTTMESSAGETEXT;
        mChatLists.get(position).isRead = 0;

        iFragmentChatView.setAdapterData(mChatLists);

        new Thread(new Runnable() {
            @Override
            public void run() {
                //把未读消息置为已读
                DatabaseManager.getInstance().clearRedCount(iFragmentChatView.getMyContext(), new String[]{"0", topic, iFragmentChatView.getSp().getString(MqttConstant.USERID, "")});
                DatabaseManager.getInstance().deleteHistory(iFragmentChatView.getMyContext(), topic, iFragmentChatView.getSp().getString(MqttConstant.USERID, ""));
                DatabaseManager.getInstance().clearTopic(iFragmentChatView.getMyContext(), topic, iFragmentChatView.getSp().getString(MqttConstant.USERID, ""));
                EventBus.getDefault().post(MqttConstant.UPDATE_RED_COUNT);

            }
        }).start();
    }


    /**
     * 退出群, 删除好友
     *
     * @param mb
     */
    private void exitGroup(MessageBean mb) {
        //退出群的 广播
        for (Iterator<MessageBean> it = mChatLists.iterator(); it.hasNext(); ) {
            MessageBean cb = it.next();
            if (mb.channelId.equals(cb.channelId)) {
                it.remove();
            }
        }

        iFragmentChatView.setAdapterData(mChatLists);

    }

    @Override
    public void clearRequest() {
        compositeDisposable.clear();
    }
}
